<!-- src/components/MarkdownRenderer.vue -->
<template>
  <div
    class="markdown-content"
    v-html="renderedContent"
    @click="handleCodeCopy"
  ></div>
</template>

<script setup>
import { computed,defineProps } from 'vue'
import { renderWithCopyButton } from '@/utils/markdownConfig'
import { ElMessage } from 'element-plus'

// 定义组件的 props
const props = defineProps({
  content: {
    type: String,
    required: true,
  },
})

// 渲染 Markdown 内容
const renderedContent = computed(() => renderWithCopyButton(props.content))

// 处理代码复制
const handleCodeCopy = (event) => {
  if (event.target.classList.contains('copy-button')) {
    const preElement = event.target.closest('pre')
    const codeElement = preElement.querySelector('code')
    const textToCopy = codeElement.textContent

    if (navigator.clipboard && navigator.clipboard.writeText) {
      // 现代浏览器 API
      navigator.clipboard.writeText(textToCopy)
        .then(() => {
          ElMessage.success('代码已复制到剪贴板')
          event.target.textContent = '已复制!'
          setTimeout(() => {
            event.target.textContent = '复制'
          }, 2000)
        })
        .catch((err) => {
          console.error('无法复制文本: ', err)
          ElMessage.error('复制失败')
        })
    } else {
      // 后备方案
      const textArea = document.createElement('textarea')
      textArea.value = textToCopy
      document.body.appendChild(textArea)
      textArea.select()
      try {
        document.execCommand('copy')
        ElMessage.success('代码已复制到剪贴板')
        event.target.textContent = '已复制!'
        setTimeout(() => {
          event.target.textContent = '复制'
        }, 2000)
      } catch (err) {
        console.error('无法复制文本: ', err)
        ElMessage.error('复制失败')
      }
      document.body.removeChild(textArea)
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/styles/markdown-content.scss';
</style>